// 导入MySQL模块
const mysql = require("mysql");
// 建立与MySQL联系
const db = mysql.createPool({
  host: "127.0.0.1", //数据库的ip地址
  user: "root", //登录数据库的账号
  password: "123456", //登录数据库的密码
  database: "task", //数据库名
});

// 查询数据
// const selectSql = "select * from studentdb";
// db.query(selectSql, (err, results) => {
//   if (err) return console.log(err.message);

//   console.log(results);
// });

// 插入数据1
const user = { name: "mask", age: 10 };
const insertSql = "insert into studentdb (name,age) values (?,?)";
db.query(insertSql, [user.name, user.age], (err, results) => {
  if (err) return console.log(err.message);
  if (results.affectedRows === 1) {
    console.log("插入成功");
  }
});

// 插入数据2
const user2 = { name: "bell", age: 20 };
const insertSql2 = "insert into studentdb set ?";
db.query(insertSql2, user2, (err, results) => {
  if (err) return console.log(err.message);
  if (results.affectedRows === 1) {
    console.log("插入成功");
  }
});

// 更新数据
const user3 = { id: 3, name: "tom", age: 22 };
const updateSql = "update studentdb set name=?,age=? where id=?";
db.query(updateSql, [user3.name, user3.age, user3.id], (err, results) => {
  if (err) return console.log(err.message);
  if (results.affectedRows === 1) {
    console.log("更新成功");
  }
});
// 更新数据2
// const user4 = { id: 4, name: "ahana", age: 30 };
// const updateSql = "update studentdb set ? where id=?";
// db.query(updateSql, [user4, user4.id], (err, results) => {
//   if (err) return console.log(err.message);
//   if (results.affectedRows === 1) {
//     console.log("更新成功");
//   }
// });

// 删除数据
const deleteSql = "delete from studentdb where id=?";
db.query(deleteSql, 3, (err, results) => {
  if (err) return console.log(err.message);
  if (results.affectedRows === 1) {
    console.log("删除成功");
  }
});

// 查询数据
const selectSql = "select * from studentdb";
db.query(selectSql, (err, results) => {
  if (err) return console.log(err.message);

  console.log(results);
});
